<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 4.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
  <head>

  	<!--<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="no-cache">
<meta http-equiv="Pragma" content="no-cache">
	<meta http-equiv="expires" content="0"> -->
  <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  <?php require_once("config.php"); ?>
  <title><?=TITLE_MAP?></title>

  <script src="js/cookie.js" type="text/javascript"></script>
  <script src="js/utils.js" type="text/javascript"></script>
  <?php if(DEBUG_MODE == 0){ ?>
  <script type="text/javascript">
  	  ctrl_FirebugActive();
  </script>
  <?php } ?>
  <?php require_once('MAPS/'.$_GET['mapType'].'/header.php'); ?>
  <style type="text/css">
  body {
    margin: 0;
    padding: 0;
    text-align: center;
	background: #E5E5E5 url(images/pageBG.jpg) repeat-x;
	overflow:hidden;
	}
  </style>
  <?php
  		require_once ("utils.php");
	  	require_once(ROOT_DIR_CLASES.'/cCliente.php');
  		require_once(ROOT_DIR_CLASES.'/log.php');
  		require_once(ROOT_DIR_CLASES.'/posiMovil.php');
		require_once(ROOT_DIR_CLASES.'/cLogin.php');
		require_once(ROOT_DIR_CLASES.'/PHPLogger.php');
  		require_once('JSON.php');

  	if (!isset($_SESSION['cliente'])) {
  		log::errorJS('Sesion expirada...');
  		exit();
  	}

	$LOGIN = unserialize($_SESSION['loginClass']);
	$json = new Services_JSON();
	$loginJSON = $json->encode($LOGIN);
	$LOGGER = new PHPLogger(LOGGER_PATH, LOGGER_LEVEL);

	/************************************************************************
	CONFIGURACION INICIAL
	*************************************************************************/
		//include("config.php");
		require_once(ROOT_DIR_CLASES.'/cResultado.php');
		require_once(ROOT_DIR_CLASES.'/cConfiguracion.php');
  		require_once(ROOT_DIR_CLASES.'/MiConfig.php');
		$cta 		= $LOGIN->cuentaFk;
		$iObjetivo 	= $LOGIN->objetivoDB;
		$esFlota 	= '0';
		if ($LOGIN->objetivoDB == 3){
			$esFlota = '1';
		}
		if ($LOGIN->objetivo == 4){
			$cta = $LOGIN->tablaId;
			$iObjetivo = $LOGIN->objetivo;
		}

		$configRegistrada = cConfiguracion::getConfig($cta, $iObjetivo);
		$miConfig = new MiConfig();
		//Puntos
		$puntosVisibles = cConfiguracion::getPuntosVisibles($cta, $iObjetivo);
		for($i = 0;  $i < $puntosVisibles->cantidad(); $i++ ) {
			$miConfig->putPuntoId($puntosVisibles->campo('PUNTO_ID',$i));
		}
		//Zonas
		$zonasVisibles = cConfiguracion::getZonasVisibles($cta, $iObjetivo);
		for($i = 0;  $i < $zonasVisibles->cantidad(); $i++ ) {
			$miConfig->putZonaId($zonasVisibles->campo('ZONA_ID',$i));
		}

		if ($configRegistrada->cantidad()>0){ //tiene configuracion inicial
			$miConfig->id = $configRegistrada->campo('ORDER_ID',0);
			//Vehiculo
			$miConfig->VEHlblformat = $configRegistrada->campo('VEH_lblformat',0);
			if (trim($miConfig->VEHlblformat)=='')
				$miConfig->VEHlblformat = VEH_LBLFORMAT;
			$miConfig->CMDtimeout = $configRegistrada->campo('CMD_timeout',0);
			if (trim($miConfig->CMDtimeout)=='')
				$miConfig->CMDtimeout = CMD_TIMEOUT;

			$miConfig->VEHsimpleview = $configRegistrada->campo('VEH_simpleview',0);
			if (trim($miConfig->VEHsimpleview)=='')
				$miConfig->VEHsimpleview = VEH_SIMPLEVIEW;
			$miConfig->VEHlblmapformat = $configRegistrada->campo('VEH_lblmapformat',0);
			if (trim($miConfig->VEHlblmapformat)=='')
				$miConfig->VEHlblmapformat = VEH_LBLMAPFORMAT;
			$miConfig->VEHlblcolor = $configRegistrada->campo('VEH_lblcolor',0);
			if (trim($miConfig->VEHlblcolor)=='')
				$miConfig->VEHlblcolor = VEH_LBLCOLOR;
			$miConfig->VEHlblsize = $configRegistrada->campo('VEH_lblsize',0);
			if (trim($miConfig->VEHlblsize)=='')
				$miConfig->VEHlblsize = VEH_LBLSIZE;
			$miConfig->VEHradio = $configRegistrada->campo('VEH_radio',0);
			if (trim($miConfig->VEHradio)=='')
				$miConfig->VEHradio = VEH_RADIO;
			$miConfig->VEHtransparencia = $configRegistrada->campo('VEH_transparencia',0);
			if (trim($miConfig->VEHtransparencia)=='')
				$miConfig->VEHtransparencia = VEH_TRANSPARENCIA;

			//Historico
			$miConfig->HIScolor = $configRegistrada->campo('HIS_color',0);
			if (trim($miConfig->HIScolor)=='')
				$miConfig->HIScolor = HIS_COLOR;
			$miConfig->HISthickness = $configRegistrada->campo('HIS_thickness',0);
			if (trim($miConfig->HISthickness)=='')
				$miConfig->HISthickness = HIS_THICKNESS;
			$miConfig->HISversentido = $configRegistrada->campo('HIS_sentido',0);
			if (trim($miConfig->HISversentido)=='')
				$miConfig->HISversentido = HIS_VERSENTIDO;
			$miConfig->HISvelexceso = $configRegistrada->campo('HIS_exceso',0);
			if (trim($miConfig->HISvelexceso)=='')
				$miConfig->HISvelexceso = HIS_VELEXCESO;
			$miConfig->HISfiltrocero = $configRegistrada->campo('HIS_filtrocero',0);
			if (trim($miConfig->HISfiltrocero)=='')
				$miConfig->HISfiltrocero = HIS_FILTROCERO;
		}
		else{ //no tiene configuracion inicial .:. levanto la configuracion por defecto...
			$miConfig->id = '';
			//Vehiculo
			$miConfig->VEHlblformat = VEH_LBLFORMAT;
			$miConfig->CMDtimeout = CMD_TIMEOUT;
			$miConfig->VEHsimpleview = VEH_SIMPLEVIEW;
			$miConfig->VEHlblmapformat = VEH_LBLMAPFORMAT;
			$miConfig->VEHlblcolor = VEH_LBLCOLOR;
			$miConfig->VEHlblsize = VEH_LBLSIZE;
			$miConfig->VEHradio = VEH_RADIO;
			$miConfig->VEHtransparencia = VEH_TRANSPARENCIA;
			//si es alias, debo buscar la configuracion por defecto de su cuentaFK
			/*if ($LOGIN->objetivo==4){
				$configFK = cConfiguracion::getConfig($LOGIN->cuentaFk, $LOGIN->objetivoDB);
				if ($configFK->cantidad()>0){ //su cuentaFK tiene configuracion inicial
					$miConfig->VEHsimpleview = $configFK->campo('VEH_simpleview',0);
					if (trim($miConfig->VEHsimpleview)=='')
						$miConfig->VEHsimpleview = VEH_SIMPLEVIEW;
					$miConfig->VEHlblmapformat = $configFK->campo('VEH_lblmapformat',0);
					if (trim($miConfig->VEHlblmapformat)=='')
						$miConfig->VEHlblmapformat = VEH_LBLMAPFORMAT;
					$miConfig->VEHlblcolor = $configFK->campo('VEH_lblcolor',0);
					if (trim($miConfig->VEHlblcolor)=='')
						$miConfig->VEHlblcolor = VEH_LBLCOLOR;
					$miConfig->VEHlblsize = $configFK->campo('VEH_lblsize',0);
					if (trim($miConfig->VEHlblsize)=='')
						$miConfig->VEHlblsize = VEH_LBLSIZE;
					$miConfig->VEHradio = $configFK->campo('VEH_radio',0);
					if (trim($miConfig->VEHradio)=='')
						$miConfig->VEHradio = VEH_RADIO;
					$miConfig->VEHtransparencia = $configFK->campo('VEH_transparencia',0);
					if (trim($miConfig->VEHtransparencia)=='')
						$miConfig->VEHtransparencia = VEH_TRANSPARENCIA;
				}
			}*/


			//Historico
			$miConfig->HIScolor = HIS_COLOR;
			$miConfig->HISthickness = HIS_THICKNESS;
			$miConfig->HISversentido = HIS_VERSENTIDO;
			$miConfig->HISvelexceso = HIS_VELEXCESO;
			$miConfig->HISfiltrocero = HIS_FILTROCERO;
			}
	/****************************************************************************/
  ?>

    <!-- CLASES MY -->
    <script src="js/myClass/MyClass.js" type="text/javascript"></script>
    <script src="js/myClass/MyLibraryManager.js" type="text/javascript"></script>
    <!-- DINAMIC INCLUDES CLASS -->
    <link href="js/progressBar/styles/ProgressBar.css" rel="stylesheet" type="text/css" />
    <script src="js/progressBar/ProgressBar.js" type="text/javascript"></script>
    <script src="js/DinamicIncludes_Map.js" type="text/javascript"></script>
	<!-- DHTMLCOMBO -->
    <link href="js/dhtmlcombo/dhtmlcombo.css" rel="stylesheet" type="text/css" />
    <script src="js/dhtmlcombo/dhtmlcombo.js" type="text/javascript"></script>
    <!-- -------------------------------------------------------------------------------------------------------------------------------- -->


    <?php
		if($LOGIN->PERMISOS[1]){ include('MMapSidebars/monitor.php');}
		if($LOGIN->PERMISOS[12]){ include('MMapSidebars/tablero.php');}
	 ?>
    <script type="text/javascript">

    IntroducirCookie('wcMapType', '<?=$_GET['mapType']?>');
	var LOGIN = null
    /**/
    var map = null;
	var mapCanvas = null; //DOMELEMENT: div en donde se carga el mapa.
	var defaultEvents = null; //control de eventos por defecto para el mapa.
    var metersPerUnit = 111319.4908;  //value returned from mapguide
    var inPerUnit = null;
	var mapIcons = null;
    /**/
	//var mapEventsHandlers = new Hashtable(); //Hashtable con Handlers de los eventos del mapa
	//var mapEventsFunctions = new Hashtable(); //Hastable con funciones de los Handlers de los eventos del mapa

	var mapActiveCursor = 'default';
    var AccordionMenu = null;
	var PopUpMenuMap = null;
    var READY_STATE_UNINITIALIZED 	= 0;
	var READY_STATE_LOADING 		= 1;
	var READY_STATE_LOADED 			= 2;
	var READY_STATE_INTERACTIVE 	= 3;
	var READY_STATE_COMPLETE 		= 4;
	var NOT_BUSY_IMAGE = "/images/loader_inactive.gif";
	var BUSY_IMAGE = "/images/loader_pulse.gif";

	var properties = null;
	var cuentaSelectSegui = <?="'".$_GET['cuentaSelectSegui']."'"?>;
	var cuentaSelectSelection = '-1';
	<? if (isset($_GET['cuentaSelectSelection'])) {?> cuentaSelectSelection = <?="'".$_GET['cuentaSelectSelection']."'"?> <? } ?>;

	var cuentaSelectTablero = '-1';
	<? if (isset($_GET['cuentaSelectTablero'])) {?> cuentaSelectTablero = <?="'".$_GET['cuentaSelectTablero']."'"?> <? } ?>;

	/*Convertir constantes PHP a JS*/
	var GEO_PROVINCIA = <?="'".GEO_PROVINCIA."'"?>;
	var GEO_CIUDAD = <?="'".GEO_CIUDAD."'"?>;
	var GEO_PAIS = <?="'".GEO_PAIS."'"?>;

	var VEH_LBLFORMAT = <?="'".$miConfig->VEHlblformat."'" ?>;
	var CMD_TIMEOUT = <?= $miConfig->CMDtimeout ?>;

	var VEH_SIMPLEVIEW = <?=$miConfig->VEHsimpleview ?>;
	var VEH_LBLMAPFORMAT = <?="'".$miConfig->VEHlblmapformat."'" ?>;
	var VEH_LBLCOLOR = <?="'#".$miConfig->VEHlblcolor."'" ?>;
	var VEH_LBLSIZE = <?="'".$miConfig->VEHlblsize."px'" ?>;
	var VEH_RADIO = <?=$miConfig->VEHradio ?>;
	var VEH_TRANSPARENCIA = <?=$miConfig->VEHtransparencia ?>;

	var COLOR_DEFAULT_RECORRIDO_INI = <?= "'".COLOR_DEFAULT_RECORRIDO_INI."'" ?>;
	var COLOR_DEFAULT_RECORRIDO_FIN = <?= "'".COLOR_DEFAULT_RECORRIDO_FIN."'" ?>;

	var MOVILES_SELECCIONADOS = '';

	var misVehiculos_limitView = <?= LIMIT_VIEWMOVILES ?>;
	var misVehiculos_limitMonitor = <?= LIMIT_LISTMONITOR ?>;
	var misVehiculos_loteo = <?= LOTE_MOVILES ?>;

	var MAXMOVILCERCA = <?= MAXMOVILCERCA ?>;

	<?	
	if (isset($_GET['movilesSELECTED'])) {?>
		MOVILES_SELECCIONADOS = <?="'".$_GET['movilesSELECTED']."'"?> ;
	<? } ?>;
	var MOVILES_MONITOR = '';
	<? if (isset($_GET['movilesMONITOR'])) {?>
		MOVILES_MONITOR = <?="'".$_GET['movilesMONITOR']."'"?> ;
	<? } ?>;
	var MOVILES_VISIBLES = cuentaSelectSegui;
	<? if (isset($_GET['movilesVISIBLES'])) {?>
		MOVILES_VISIBLES = <?="'".$_GET['movilesVISIBLES']."'"?> ;
	<? } ?>;

	var PERMISOS_BYKOM = new Array(0,0,0,0,0);
	var OPENER_BYKOM = 0;
	<? if (($LOGIN->isBykom)&&(isset($permisosBykomString))) {?>
	    OPENER_BYKOM = 1;
		PERMISOS_BYKOM = new Array();
		var arrayStrValues = '<?=$permisosBykomString ?>';
		for (var i=0; i < arrayStrValues.length; i++){
			PERMISOS_BYKOM.push(arrayStrValues.substr(i,1));
			}
	<? } ?>;

	var movilHIS = null;
	<? if (isset($_GET['movilHIS'])) {?> movilHIS = <?="'".$_GET['movilHIS']."'"?> <? } ?>;
	var desdeHIS = null;
	<? if (isset($_GET['desdeHIS'])) {?> desdeHIS = <?="'".$_GET['desdeHIS']."'"?> <? } ?>;
	var hastaHIS = null;
	<? if (isset($_GET['hastaHIS'])) {?> hastaHIS = <?="'".$_GET['hastaHIS']."'"?> <? } ?>;

	var COLOR_DEFAULT_ZONA_GMAP = '<?= $miConfig->HIScolor; ?>';
	var PUNTOSVISIBLES_string = '<?= join(",", $miConfig->PUNTOSVISIBLESid); ?>';
	var ZONASVISIBLES_string = '<?= join(",", $miConfig->ZONASVISIBLESid); ?>';

	/*FLAGS*/
	var autoRefreshFlag = 0;
	var monitorActivoFlag = false;
	var vehiculosCargadosFlag = false;

    //FUNCIONES DE CENTRADO EN EL MAPA
	function centrar(latitud, longitud) {
		var lonlat = new OpenLayers.LonLat(parseFloat(longitud), parseFloat(latitud)).transform(displayProjection, projection);
		map.panTo(lonlat);
	}

	function centrarEnBounds(bounds) { //centra el mapa en un bounds y hace zoom para que se contenga.
		if(bounds != null) {
			map.zoomToExtent(bounds);
		}
	}

	function centrarEnPoly(poly) { //centra el mapa en un Polygon o una Polyline y ajusta niveles de zoom para que se vea todo.
		if(poly != null) {
  			bounds = poly.getBounds(); //retorna los limites de la poly
 			map.setCenter(bounds.getCenter());
 			map.setZoom(map.getBoundsZoomLevel(bounds));
			}
	}


/****************************(REFRESH)********************************/

	function OnReadyStateChange() {
    	var ready = reqHandler.readyState;
		if (ready == READY_STATE_COMPLETE) {
			<?php if(DEBUG_MODE == 0){ ?>
			//controlo que firebug no este activo
				ctrl_FirebugActive();
			<?php } ?>
			//si los vehiculos aun no estan cargados en su hash reintento cargarlos...
			if (misVehiculosHash.isEmpty()){
				CargarMisVehiculos();
			}

			//refresh POSICIONES DE VEHICULOS
			results = reqHandler.responseText.parseJSON();
			if (results.length != 'undefined') {
				var resultsLarge = results.length;
				if(LOGIN.PERMISOS[10]){ //chat habilitado
					resultsLarge = results.length - 1;
				}

				for (var i = 0; i < resultsLarge; i++) {
					var movilAnterior = misVehiculosHash.get(results[i].id);
					if (movilAnterior != null){
						var latitud = 0;
						var longitud = 0;
						if (movilAnterior.POSIMOVIL != null) {
							latitud =  movilAnterior.POSIMOVIL.latitud;
							longitud = movilAnterior.POSIMOVIL.longitud;
						}
						misVehiculosHash.get(results[i].id).POSIMOVIL = results[i];
						if (latitud != results[i].latitud || longitud != results[i].longitud) {
							if (VEH_SIMPLEVIEW)
								putSimpleIconCar(results[i].id);
							else
								putIconCar(results[i].id);
						}

					}
				}
				if (LOGIN.PERMISOS[10]){
					if(results[resultsLarge]>0){ //EXISTEN MENSAJES EN CHAT ALIVE!
						document.getElementById('alertChatIncomming').title='Usted tiene '+results[resultsLarge-1]+' mensajes sin leer en Chat Live!';
						document.getElementById('alertChatIncomming').style.display = "block";
					   }
					else document.getElementById('alertChatIncomming').style.display = "none";
				}
				//refreshViewMisVehiculos();
			}

			//refresh panel SEGUIMIENTO
			refreshMovilSeguimiento();
			//refresh panel SELECCION
			refreshMovilSelection();
			//refresh TABLERO
			if ((LOGIN.PERMISOS[12])&&(tableroContainer.isVisible))
				refreshMovilTablero();
			//refresh eventos en MONITOR
			if ((vehiculosCargadosFlag)&&(LOGIN.PERMISOS[1]))
				//CargarEventosMonitor();

			document.getElementById("busyImg").style.visibility = "hidden";
			autoRefreshFlag = 0;
			reqHandler = null;
		}
    }

	function RefreshForm() {
		if ((!vehiculosCargadosFlag)||(autoRefreshFlag==1)) return;
    	autoRefreshFlag = 1;
    	document.getElementById("busyImg").style.visibility = "visible";
		var reqParamsRefreshForm = "COMMAND=REFRESH";
		reqParamsRefreshForm += "&cuentas=" + vehiculosVisiblesId.join(",");
		if(LOGIN.PERMISOS[10]){ //chat habilitado
			reqParamsRefreshForm += "&TABLAID="+LOGIN.tablaId;
			reqParamsRefreshForm += "&OBJETIVO="+LOGIN.objetivo;
		}
    	if (msie)
            reqHandler = new ActiveXObject("Microsoft.XMLHTTP");
        else
            reqHandler = new XMLHttpRequest();
        reqHandler.onreadystatechange = OnReadyStateChange;
        reqHandler.open("POST", "querycontroller.php", true);
        reqHandler.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		reqHandler.send(reqParamsRefreshForm);
    }

	function AutoRefreshForm() {
    	if (autoRefreshFlag == 0) {
    		RefreshForm();
    	}
    }

	var menuVisible = true;
	function collapseMenuBar(){
		mapWidth = mapCanvas.offsetWidth;
		if (menuVisible){
			accordionWidth = document.getElementById('AccordionMenu').offsetWidth;
			document.getElementById('sliceMenuBarIcon').className = 'sliceMenuBarIconIn';
			menuVisible = false;
			document.getElementById('gMapMenuBar').style.width='10px';
			document.getElementById('AccordionMenu').style.display = "none";
			document.getElementById('gMapMainContent').style.marginRight ='18px';
		}
		else{
			document.getElementById('sliceMenuBarIcon').className = 'sliceMenuBarIconOut';
			menuVisible = true;
			document.getElementById('gMapMenuBar').style.width='325px';
			document.getElementById('AccordionMenu').style.display = "block";
			document.getElementById('gMapMainContent').style.marginRight = '333px';
		}
		//map.render(mapCanvas);
		map.updateSize();
		//map.render(mapCanvas); //lo repito por bug en eventos para ie 8
		if ((tableroContainer != null)&&(tableroContainer.isVisible))
			tableroContainer.redraw();
	}

	var toMapType = '<?= $_GET['mapType']?>';
	function changeMapServer(mapType){
		toMapType = mapType;
		var centerLonLat = map.getCenter().transform(projection, displayProjection);
		var URL = "map.php?v=" + <?="'".$_GET['v']."'"?> + "&cuenta=" + <?="'".$_GET['cuenta']."'"?> + "&cuentaSelectSegui=" + cuentaSelectSegui + "&cuentaSelectSelection=" + cuentaSelectSelection + "&cuentaSelectTablero=" + cuentaSelectTablero + "&y=" + centerLonLat.lon + "&x=" + centerLonLat.lat + "&mapType=" + mapType;
		var URLmoviles = '&movilesSELECTED='+vehiculosSeleccionadosId.toString();
		URLmoviles += '&movilesMONITOR='+vehiculosMonitoreadosId.toString();
		URLmoviles += '&movilesVISIBLES='+vehiculosVisiblesId.toString();

		var URLhistorico = "&movilHIS=" + document.getElementById('cuentaSelectHistorico').value;
		URLhistorico += "&desdeHIS=" + document.getElementById('fechaInicio').value;
		URLhistorico += "&hastaHIS=" + document.getElementById('fechaFin').value;
		if (OPENER_BYKOM == 1) {
			URL = "mapBykom.php?ORDERID=<?=$_REQUEST['ORDERID']?>&ESFLOTA=<?=$_REQUEST['ESFLOTA']?>&cuentaSelectSegui=<?=$_REQUEST['cuentaSelectSegui']?>&mapType=" + mapType +"&PUBLICKEY=<?=$_REQUEST['PUBLICKEY']?>&USUARIOID=<?=$_REQUEST['USUARIOID']?>&y=<?=$_GET['y']?>&x=<?=$_GET['x']?>";
			URLmoviles = "";
			URLhistorico = "";
		}
		/*var reloadpage = "changemap_ie.php?urlreload="+escape(URL + URLmoviles + URLhistorico);
			self.location.href = reloadpage;*/
		if (msie)
			window.opener.refreshPopUpMapa(URL + URLmoviles + URLhistorico);
		else
			self.location.href = URL + URLmoviles + URLhistorico;
	}

	function closeOrRefreshMap(evt, mapType){
		if (msie){
			var e = (window.event) ? window.event : evt;
			if (e.clientX < 0 || e.clientY < 0){
				return;
			}
			else{
				//alert(toMapType);
				changeMapServer(toMapType);
			}
		}
		unload();
	}
    </script>



  </head>
  <body onload="loadlibraries();" onunload="closeOrRefreshMap(event);" onResize="resizear()">

  <div id="mapLoadingPanel" style="width:100%; height:568px; background:#CCCCCC; top:0; left:0; position:absolute; z-index:2000; opacity:0.8; overflow:hidden;">
    	<table width="100%" height="100%" border="0"><tr><td align="center" valign="middle">
            <img border="0" src="images/loader.gif" /><br />
			<span style="color:#666666; font-size:9px; font-family:Verdana, Arial, Helvetica, sans-serif">CARGANDO...</span><br />
			<div id="mapLoadingBar" style="width:350px; height:40px;"></div>
        </td></tr></table>
  </div>

  <!-- DIVS PARA FUNCIONAMIENTO DEL DHTML WINDOW -->
  <div id="dhtmlwindowholder"><span style="display:none">.</span></div>
  <div id="interVeil"></div>
  <!-- ----------------------------------------- -->

  <div id="gMapContainer" style="visibility:hidden;">
    <div id="gMapHeader" style="width:100%;">
    	<table id="map_selector_table" cellpadding="0" cellspacing="0" border="0" width="100%" height="58"><tr>
        	<td width="100%">
            	<select id="serversMapSelect">
					<option value="changeMapServer('bykom');">Bykom Maps</option>
					<option value="changeMapServer('google');">Google Maps</option>
					<option value="changeMapServer('yahoo');">Yahoo!</option>
					<option value="changeMapServer('virtualearth');">Microsoft Virtual Earth</option>
                    <option value="changeMapServer('openstreet');">Open Street Maps</option>
				</select>
                <script type="text/javascript">
					//inicializo el Combo Selector de Mapas
					combodropimage='<img class="downimage" src="MAPS/'+<?= "'".$_GET['mapType']."'"?>+'/mapsLogo.gif" title="Cambiar servidor de mapas" />';
					dhtmlselect("serversMapSelect", "0px", "200px");
				</script>
            </td>
            <td width="300px">
            	<?php if ($LOGIN->isPRO){ ?>
            	<div style="height:58px; width:300px; background:url(imagenes/logomapsPro.jpg) center no-repeat; float:right; text-align:right;">
                <?php } else { ?>
				<div style="height:58px; width:300px; background:url(imagenes/logomaps.jpg) center no-repeat; float:right; text-align:right;">
                <?php } ?>
                	<div style="width:100%; height:20px;"><img id="busyImg" src="images/loader_pulse.gif" style="vertical-align:bottom" align="right"></div>
                    <div style="width:100%"><img id="alertChatIncomming" src="images/chat/alertChatIncomming.gif" style="vertical-align:bottom; display:none;" align="right"></div>
                </div>
            </td>
        </tr>
        </table>
    </div>

    <div id="gMapMenuBar">

        <!-- DIV generico para crear el contenido de las ventanas DHTMLWindow -->
        <div id="genericDHTMLWindowDiv" style="display:none; text-align:left;" align="left"></div>
        <table cellpadding="0" cellspacing="0" border="0" height="100%" width="100%">
        <tr>
        <td width="10" valign="middle" align="center" style="background:#E3E3E3 url(images/collapsableBarBG.gif) repeat-y; cursor:pointer;" bgcolor="#FFC0C0" onClick="collapseMenuBar();" >
        	<div id="sliceMenuBarIcon" class="sliceMenuBarIconOut"></div>
        </td>
        <td valign="top">
 	    <div id="AccordionMenu" class="Accordion" tabindex="0">

	  	<?php
	  		include('GMapPanels/vehiculos2.php');
			include('GMapPanels/seguimiento.php');
			include('GMapPanels/seleccion.php');
			if($LOGIN->objetivo == 4){
				if($LOGIN->PERMISOSAlias[3]){
					include('GMapPanels/historico.php');
				}
			}else{
				include('GMapPanels/historico.php');
			}
			if ($LOGIN->PERMISOS[4])
				include('GMapPanels/mispuntos.php');
			if ($LOGIN->PERMISOS[5])
				include('GMapPanels/miszonas.php');
			if ($LOGIN->PERMISOS[6])
				include('GMapPanels/reglas.php');
			include('GMapPanels/miscelaneas.php');
		?>
		</div>
        </td>
        </tr>
        </table>
    </div>
    <div id="gMapMainContent">
    	<div id="map_canvas" oncontextmenu="return false;"></div>
    </div>
  </div>

<?php include ('MAPS/'.$_GET['mapType'].'/initialize.php');
      $fecha=mktime(0,0,0,1,1,2010);
      setcookie('wcMapType',$_GET['mapType'],' ',' ',0);?> <!-- incluye todas las funciones ...Body() para el mapa en cuestion -->
<script>
	function initMapEvents() {
		map.events.on({
			"addlayer": function(){
				var MarkersLayers = map.getLayersByClass(vehiculosLayer.CLASS_NAME);
				for (var i=0; i<MarkersLayers.length; i++){
					MarkersLayers[i].div.style.zIndex = 900;
				}
			},
			"removelayer": function(){
				var MarkersLayers = map.getLayersByClass(vehiculosLayer.CLASS_NAME);
				for (var i=0; i<MarkersLayers.length; i++){
					MarkersLayers[i].div.style.zIndex = 900;
				}
			}
		});

		OpenLayers.Control.DefaultEvents = OpenLayers.Class(OpenLayers.Control, {
                defaultHandlerOptions: {
                    'single': true,
                    'double': true,
                    'pixelTolerance': 0,
                    'stopSingle': false,
                    'stopDouble': false
                },

                initialize: function(options) {
                    this.handlerOptions = OpenLayers.Util.extend(
                        {}, this.defaultHandlerOptions
                    );
                    OpenLayers.Control.prototype.initialize.apply(
                        this, arguments
                    );
                    this.handler = new OpenLayers.Handler.Click(
                        this, {
                            'click': this.onClick,
							'dblclick': this.onDblClick
                        }, this.handlerOptions
                    );
                },

                onClick: function(e) {
				},

				onDblClick: function(e) {
				}
            });

		if (LOGIN.PERMISOS[7])
			initMisPuntosEvents();
		if (LOGIN.PERMISOS[8])
			initMisZonasEvents();

		defaultEvents = new OpenLayers.Control.DefaultEvents();
        map.addControl(defaultEvents);
        defaultEvents.activate();
	}

	var mapOptions;
	var projection; //proyeccion del mapa
	var displayProjection; //proyeccion del display
	var monitorButton = null;
	var tableroContainer = null;

	function loadlibraries(){
		document.getElementById('mapLoadingPanel').style.display = "block";
		dinamicIncludes_Map.includePreload();
	}

	function initialize() {
		//document.getElementById('mapLoadingPanel').style.display = "block";
		//dinamicIncludes_Map.includePreload();
		//dinamicIncludes_Map.includeGeneral();
		resizear();
	  	document.getElementById("busyImg").style.visibility = "hidden";
	  	AccordionMenu = new Spry.Widget.Accordion("AccordionMenu");
		initializeBody();

		//Controles OpenLayers
		map.addControl(new OpenLayers.Control.MousePosition());

		//INIT MAP.Z-INDEX BASE ARRAY
		map.Z_INDEX_BASE['Popup']=999;

		//creo e inicio el selectMenu TOOLS
		var toolMeasure = new OpenLayers.Control.ToolMeasure();
		map.addControl(toolMeasure);
		var toolArea = new OpenLayers.Control.ToolArea();
		map.addControl(toolArea);
		var selectToolsMenu = new OpenLayers.Control.SelectSwitcher({buttonText:'Tools', width:'100px', right:'126px'});
		selectToolsMenu.addItem('Medir Distancia', function(){if(toolArea.isActive)toolArea.deactivate(); toolMeasure.activate();});
		selectToolsMenu.addItem('Calcular Area', function(){if(toolMeasure.isActive)toolMeasure.deactivate(); toolArea.activate();});
		map.addControl(selectToolsMenu);
		//creo e inicio el tablero
		if (LOGIN.PERMISOS[12]){
			//dinamicIncludes_Map.includeTablero();
			tableroContainer = new OpenLayers.Control.TableroContainer({isVisible:false});
			tableroContainer.addContent('tablero_content');
			map.addControl(tableroContainer);
			}

		//creo e inicio el Monitor
		if (LOGIN.PERMISOS[1]) {
			var monitorScrollList = document.getElementById('monitorListScroll');
			var monitorContainer = new OpenLayers.Control.MonitorContainer({containerTitle:'Monitor', isVisible:false, listElement:monitorScrollList});
			monitorContainer.addContent('monitor_content');
			monitorButton = new OpenLayers.Control.MonitorButton({buttonText:'Monitor', width:'100px', right:'239px'});
			map.addControl(monitorButton);
			map.addControl(monitorContainer);
			monitorButton.setContainer(monitorContainer);
			}

		var lonlat = new OpenLayers.LonLat(parseFloat(<?=$_GET['y']?>), parseFloat(<?=$_GET['x']?>)).transform(displayProjection, projection);
		map.setCenter(lonlat , INITIAL_MAP_ZOOM);
		//carga de moviles (y grupos de moviles)
		dinamicIncludes_Map.setMessage('Cargando MOVILES...');
		CargarMisGruposVehiculos();
		//-------------------------------------
        RefreshForm();
		initMapEvents();
		resizear();
		setInterval("AutoRefreshForm();", eval(<?= GMAP_MAPA_REFRESH_AVL ?>) * 1000);
		jscolor.init();
    }

	 function handleMeasurements(event) {
            var geometry = event.geometry;
            var units = event.units;
            var order = event.order;
            var measure = event.measure;
            var out = "";
            if(order == 1) {
                out += "measure: " + measure.toFixed(3) + " " + units;
            } else {
                out += "measure: " + measure.toFixed(3) + " " + units + "<sup>2</" + "sup>";
            }
        }

	function unload(){
		unloadBody();
	}

    function resizear() {
    	var theHeight = 0;
    	if (window.innerHeight) {
    		theHeight=window.innerHeight;
    	}
    	else if (document.documentElement && document.documentElement.clientHeight) {
    		theHeight=document.documentElement.clientHeight;
    	}
    	else if (document.body) {
    		theHeight=document.body.clientHeight;
    	}
    	if (theHeight > 590){
    		mapHeight = theHeight - 90;
    	}
    	else {
    		mapHeight = 500;
    	}

		document.getElementById('gMapMenuBar').style.height = mapHeight + "px";
		document.getElementById('mapLoadingPanel').style.height = theHeight + 'px';

		if (dinamicIncludes_Map.isGeneralInclude()){
			mapCanvas.style.height = mapHeight + "px";
			if (map!=null){
				//map.render(mapCanvas);
				map.updateSize();
				//map.render(mapCanvas); //lo repito por bug en eventos para ie 8
				}
			if (monitorButton != null)
				monitorButton.redraw();
			if (tableroContainer != null)
				tableroContainer.redraw();
		}
    }

    function cleanAllStates(){
		if (LOGIN.PERMISOS[0])
			cleanEstadoNuevoGrupoVehiculos();
		if ((LOGIN.PERMISOS[7])&&(dinamicIncludes_Map.isMisPuntosInclude())){
    		cleanEstadoNuevoPunto();
	    	cleanEstadoModificarPunto();
    		cleanEstadoBuscarPunto();
    		cleanEstadoNuevoGrupo();
			}
		if ((LOGIN.PERMISOS[8])&&(dinamicIncludes_Map.isMisZonasInclude()))
	    	cleanEstadoNuevaZona();
		if ((LOGIN.PERMISOS[9])&&(dinamicIncludes_Map.isLogisticaInclude())){
    		cleanEstadoNuevaRegla();
    		cleanEstadoAplicarRegla();
			}
    }

	function initializeGlobalVars(){
		LOGIN = '<?= $loginJSON ?>'.parseJSON();
		mapCanvas = document.getElementById('map_canvas');
		inPerUnit = OpenLayers.INCHES_PER_UNIT.m * metersPerUnit;
		OpenLayers.INCHES_PER_UNIT["dd"] = inPerUnit;
	    OpenLayers.INCHES_PER_UNIT["degrees"] = inPerUnit;
    	OpenLayers.DOTS_PER_INCH = 96;
		mapIcons = new MapIcons({
						misPuntos: LOGIN.PERMISOS[4]
					});
	}

	var _loadingBar = new ProgressBar({
								width: '150px',
     							container: 'mapLoadingBar'
     						  });

</script>
</body>
</html>